package pub.elephants.serializable.impl;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import pub.elephants.serializable.ElephantsSerializable;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class HessianSerializer extends ElephantsSerializable {
    /**
     * serializable
     *
     * @param obj
     * @return
     */
    public <T> byte[] serializable(T obj) throws IOException {
        if (obj == null)
            throw new NullPointerException();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        HessianOutput output = new HessianOutput(outputStream);
        output.writeObject(obj);
        return outputStream.toByteArray();
    }

    /**
     * un serializable
     *
     * @param bytes
     * @param clazz
     * @return
     */
    public <T> T unSerializable(byte[] bytes, Class<T> clazz) throws IOException {
        if (bytes == null)
            throw new NullPointerException();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        HessianInput input = new HessianInput(inputStream);
        return (T)input.readObject();
    }
}
